#include "CommonDialog.h"
#include "ShellControl.h"

namespace FreeCL
{

OpenDialog::OpenDialog()
{	
}						    

#ifndef OFN_FORCESHOWHIDDEN
#define OFN_FORCESHOWHIDDEN          0x10000000
#endif

void OpenDialog::CreateOpenDialog(WinContainer* parent,OpenDialogDesc& desc)
{	  
	memset(&mInfo,0,sizeof(mInfo));
	mInfo.lStructSize = sizeof(mInfo);
	
	if(parent && parent->GetHandle())
		mInfo.hwndOwner = parent->GetHandle();
	
	_StrCpy(mFilter, desc.mFilter.c_str());
	int len = (int)_StrLen(mFilter);
	for(int i = 0; i < len; i++)
	{
		if(mFilter[i] == TCHAR('|'))
			mFilter[i] = TCHAR('\0');
	}
	if(len+2 <= sizeof(mFilter))
		mFilter[len+1] = TCHAR('\0');
	mInfo.lpstrFilter = mFilter;

	mInfo.nFilterIndex = desc.mFilterIndex + 1;

	mPath[0] = 0;
	mInfo.lpstrFile = mPath;

	mInfo.nMaxFile = sizeof(mPath);

	if(desc.mInitialDir.length())
	{
		mInitialDir = desc.mInitialDir; 
		mInfo.lpstrInitialDir = mInitialDir.c_str();
	}
	
	if(desc.mTitle.length())
	{
		mTitle = desc.mTitle;
		mInfo.lpstrTitle = mTitle.c_str();
	}

	if(desc.mMultiSelect)
		mInfo.Flags |= OFN_ALLOWMULTISELECT;
	if(desc.mCanResize)
		mInfo.Flags |= OFN_ENABLESIZING;
	if(!desc.mExplorerStyle)
	{
		mInfo.Flags |= OFN_ENABLEHOOK;
		mInfo.lpfnHook = &OpenDialog::SimpleHookProc;
		mExplorerStyle = false;
	}
	else
	{
		mInfo.Flags |= OFN_EXPLORER;
		mExplorerStyle = true;
	}
	mInfo.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
	if(desc.mShowHidden)
		mInfo.Flags |= OFN_FORCESHOWHIDDEN;
	mInfo.Flags |= OFN_LONGNAMES;//old-style single-select dialog use long file name
	mInfo.Flags |= OFN_NOCHANGEDIR;
}

bool OpenDialog::ShowDialog()
{					
	mFileList.clear();
	if(GetOpenFileName(&mInfo))
	{
		char sep;
		if(mExplorerStyle)
			sep = '\0';
		else
			sep = ' ';

		String path;
		String file;
		if(mPath[mInfo.nFileOffset-1] == sep)
		{
			if(mExplorerStyle)
			{
				path = mPath;
				path += TEXT("\\");
			}
			else
			{
				mPath[mInfo.nFileOffset-1] = TCHAR('\0');
				path = mPath;
				mPath[mInfo.nFileOffset-1] = sep;
			}
			int offset = mInfo.nFileOffset;

			while(true)
			{
				file = TEXT("");
				while(mPath[offset] != sep && mPath[offset] != TCHAR('\0'))
				{
					file += mPath[offset];
					offset++;
				}
				mFileList.push_back(path+file);
				if(!mExplorerStyle && mPath[offset] == TCHAR('\0'))
					break;
				offset++;
				if(mExplorerStyle && mPath[offset] == sep)
					break;
			}
		}
		else
			mFileList.push_back(String(mPath));
		return true;
	}
	return false;
}

UINT_PTR CALLBACK OpenDialog::SimpleHookProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
	return FALSE;
}

void SaveDialog::CreateSaveDialog(WinContainer* parent,SaveDialogDesc& desc)
{
	CreateOpenDialog(parent,desc);
	mInfo.Flags &= ~(OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT);
	if(desc.mPromptExist)
		mInfo.Flags |= OFN_OVERWRITEPROMPT;
}

}